import 'package:flutter/material.dart';

class VolumeSlider extends StatefulWidget {
  final double value; // 当前音量 0.0~1.0
  final ValueChanged<double>? onChanged; // 拖动时回调
  final ValueChanged<double>? onChangeEnd; // 拖动结束回调

  const VolumeSlider({
    super.key,
    required this.value,
    this.onChanged,
    this.onChangeEnd,
  });

  @override
  State<VolumeSlider> createState() => _VolumeSliderState();
}

class _VolumeSliderState extends State<VolumeSlider> {
  late double _value;

  @override
  void initState() {
    super.initState();
    _value = widget.value;
  }

  void _updateValue(Offset localPosition, double width) {
    double newValue = (localPosition.dx / width).clamp(0.0, 1.0);
    setState(() => _value = newValue);
    widget.onChanged?.call(newValue);
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        double width = constraints.maxWidth;
        double height = 40;

        return GestureDetector(
          onHorizontalDragUpdate: (details) {
            _updateValue(details.localPosition, width);
          },
          onHorizontalDragEnd: (_) {
            widget.onChangeEnd?.call(_value);
          },
          onTapDown: (details) {
            _updateValue(details.localPosition, width);
          },
          child: CustomPaint(
            size: Size(width, height),
            painter: _VolumeSliderPainter(_value),
          ),
        );
      },
    );
  }
}

class _VolumeSliderPainter extends CustomPainter {
  final double value;

  _VolumeSliderPainter(this.value);

  @override
  void paint(Canvas canvas, Size size) {
    final double radius = size.height / 2;

    final Paint bgPaint = Paint()
      ..color = Colors.grey.shade300
      ..style = PaintingStyle.fill;

    final Paint fillPaint = Paint()
      ..shader = const LinearGradient(
        colors: [Colors.blue, Colors.blueAccent],
      ).createShader(Rect.fromLTWH(0, 0, size.width * value, size.height));

    // 背景圆角条
    final RRect bgRect = RRect.fromLTRBR(
      0,
      0,
      size.width,
      size.height,
      Radius.circular(radius),
    );
    canvas.drawRRect(bgRect, bgPaint);

    // 已选进度
    final RRect fillRect = RRect.fromLTRBR(
      0,
      0,
      size.width * value,
      size.height,
      Radius.circular(radius),
    );
    canvas.drawRRect(fillRect, fillPaint);

    // 滑块
    final double thumbX = size.width * value;
    final Offset thumbCenter = Offset(thumbX, size.height / 2);
    final Paint thumbPaint = Paint()..color = Colors.white;
    canvas.drawCircle(thumbCenter, size.height / 2 - 4, thumbPaint);

    // 阴影
    canvas.drawCircle(
      thumbCenter.translate(2, 2),
      size.height / 2 - 4,
      Paint()..color = Colors.black.withOpacity(0.2),
    );
  }

  @override
  bool shouldRepaint(covariant _VolumeSliderPainter oldDelegate) {
    return oldDelegate.value != value;
  }
}
